<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
	/**
	 * @var string the default layout for the controller view. Defaults to 'application.views.layouts.column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='application.views.layouts.column2';
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu=array();
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $rmenu=array();
	
	public $col1 = '';
	
	public $col2 = '';

        public $sidebar = '';
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();

    public function AssignData(&$ref,$class) {
        if(!isset($_POST[$class]))
        	return;
        foreach($_POST[$class] as $i=>$item) {
            $ref[$i] = new $class;
            $ref[$i]->attributes = $item;
            $i++;
        }
    }
    public function makeErrorByName($item = array(),$css='error') {
        $js='';
        foreach($item as &$_item) {
            $_item = "form input[name='$_item']";
        }
        $selector = implode(',',$item);
        if($selector!='')
            $js.="$(\"$selector\").addClass('$css');";
        return $js;
    }
    public function makeErrorByValue($item = array(),$css='error') {
        $g=0;
        $condition = '';
        $js='';
        foreach($item as $_item) {
           if($g>0)
                    $condition .= ' || ';
                $condition .= 'yval=="'.$_item.'"';
            $g++;
        }
        if($condition!='') {
            $js = "$('form input').each(function(){var yval = $(this).val(); if($condition){ $(this).addClass('$css');} });";;
        }
        return $js;
    }
    public function makeErrorMsg($error = array(),$header=null,$footer=null,$htmlOptions=array()) {
        $content='';
        foreach($error as $err) {
            if($err!='')
                $content.="<li>$err</li>";
        }
        if($content!=='') {
            if($header===null)
                $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
            if(!isset($htmlOptions['class']))
                $htmlOptions['class']=CHtml::$errorSummaryCss;
            return CHtml::tag('div',$htmlOptions,$header."<ul>$content</ul>".$footer);
        }
        else
            return '';
    }
    public function makeJsErrorMsg($error,$container='errorsummary') {
        return ($error!='')?"$('#$container').html('$error');":'';
    }
    private function encodeSelector($str){
        $ary = array('#'=>'\\#',';'=>'\\;','&'=>'\\&',','=>'\\,','.'=>'\\.','+'=>'\\+','*'=>'\\*','~'=>'\\~',':'=>'\\:','"'=>'\\"','!'=>'\\!','^'=>'\\^','$'=>'\\$','['=>'\\\[',']'=>'\\\]','('=>'\\(',')'=>'\\)','='=>'\\=','>'=>'\\>','|'=>'\\|','/'=>'\\/',"'"=>"\\'");
        return strtr($str,$ary);
    }
    public function getErrorName($model,$header=null,$footer=null,$htmlOptions=array()){
        $errorAttri = array();
        $errorSummary = array();
        $returnVal ='';
        if(!is_array($model))
            $model = array($model);
        foreach($model as $m) {
            if($m instanceof CActiveRecord) {
                foreach($m->getErrors() as  $name=>$err) {
                    $errorAttri[CHtml::resolveName($m, $name)]=$err[0];
                    $errorSummary[]=$err[0];
                }
            }
            elseif(is_array($m) && $m[0] instanceof CActiveRecord) {
                foreach($m as $i=>$_m) {
                    $err1 = array();
                    foreach($_m->getErrors() as $n=>$e) {
                        $_n = "[$i]".$n;
                        $errorAttri[CHtml::resolveName($_m, $_n)]=$e[0];
                        if(!in_array($e[0],$errorSummary))
                            $errorSummary[] = $e[0];
                    }
                }
            }
        }
        return array('attr'=>$errorAttri,'summary'=>$this->makeErrorMsg($errorSummary,$header=null,$footer=null,$htmlOptions=array()));
    }
    public function makeModelError($model,$header=null,$footer=null,$htmlOptions=array()) {
        $r = $this->getErrorName($model,$header=null,$footer=null,$htmlOptions=array());
        $returnVal = $this->makeErrorByName($r['attr']);
        $returnVal .= $this->makeJsErrorMsg($r['summary']);
        return $returnVal;
    }
    
    public function validateModels($models = array(),$replacement = array(),$endreplacement = array()){
    	if(!Yii::app()->request->isAjaxRequest)
    		return;
    	$error = false;
    	$errorAttri = array();
    	$errorSummary = array();
    	if($models instanceof CActiveRecord)
    		$models = array($models);	
    	foreach($models as $model){
    		if($model instanceof CActiveRecord) {
    			if(!$model->validate()) {
    				$error = true;
    				foreach($model->getErrors() as  $name=>$err) {
    					if(isset($replacement[$name]))
                    		$name = $replacement[$name];
                    	$errorAttri[CHtml::getIdByName(CHtml::resolveName($model, $name))]=$err[0];
                    	$errorSummary[]=$err[0];
                	}
    			}
            }
            elseif(is_array($model)) {
                foreach($model as $key=>$_model) {
                    if($_model instanceof CActiveRecord) {
                    	if(!$_model->validate()) {
                    		$error = true;
                    		foreach($_model->getErrors() as  $name=>$err) {
                    			if(isset($replacement[$name]))
                    				$name = $replacement[$name];
    							$name = '['.$key.']'.$name;
                    			$errorAttri[CHtml::getIdByName(CHtml::resolveName($_model, $name))]=$err[0];
                    			$errorSummary[]=$err[0];
                			}                    		
                    	}
                	}
                }
            }
    	}
    	if($error) {
    		foreach($endreplacement as $key=>$value){
    			if(isset($errorAttri[$key])) {
    				$errorAttri[$value] = $errorAttri[$key];
    				unset($errorAttri[$key]);
    			} 
    		}
    		echo CJavaScript::jsonEncode(array('attr'=>$errorAttri,'summary'=>$this->makeErrorMsg($errorSummary)));
        	Yii::app()->end();
    	}
    }
    public function saveMore2More($ref) {
        $ID = null;
        foreach($this->$ref as $item) {
            if($item->$ref != 0 && !empty($item->$ref) && $item->$ref != '')
            {
                $_id = $item->save();
                if($_id===false) {
                    return false;
                }
                if($_id != 0)
                    $ID[] = $_id;
            }
        }
        $db = $this->dbConnection;
        $criteria = new CDbCriteria;
        $criteria->condition = 'cargo_id = :cargo_id';
        $criteria->params = array(':cargo_id'=>$this->id);
        if(!$this->isNewRecord) {
            if($db->commandBuilder->createDeleteCommand("cargo_join_".$ref,$criteria)->execute() === null){
                return false;
            }
        }
        foreach($ID as $item) {
            $db->commandBuilder->createInsertCommand("cargo_join_".$ref,array('cargo_id'=>$this->id,$ref."_id"=>$item))->execute();
        }
        return true;
    }
    public function SaveMany($model,$foreignModel,$foreignKey,$ValuetoKey = array()){
    	$foreignModel[0]->deleteAll($foreignKey.' =:key',array(':key'=>$model->id));
    	foreach($foreignModel as &$item){
    		foreach($ValuetoKey as $key=>$value){
    			$item->$key = $value;
    		}
            if(!$model->Add(&$item,$foreignKey))
            	return false;
        }
        return true;
    }
    public function checkModels($models){
    	if(!is_array($models))
    		$models = array($models);
    	try {
    		foreach($models as $model) {
    			if(is_array($model)) {
    				foreach($model as $subModel){
    					if($subModel instanceof CActiveRecord && $subModel != null) { 
    						//Do Nothing 
    					}
    					else
    						 throw new CException();
	    			}
    			}
    			else{
    				if($model != null && $model instanceof CActiveRecord){
    					//Do nothing
    				}
    				else
    					throw new CException();
    			}
    		}
    	}
    	catch(CException $e){
    		throw new CHttpException(400,"Invalid request. Please do not repeat again.");
    	}
    }
	public function getModel($model=null,$getter='') {
		if($model == null || !isset($_GET[$getter]))
			throw new CHttpException(404,'The requested page does not exist.');
		
        if($model instanceof CActiveRecord) {
        	$model = $model->findByPk($_GET[$getter]);
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $model;
    }
}